// FILE: Chip8ROM.cpp by Richard Hughes 27/04/2012
//
// DESC: Implements the Chip8 ROM

// INCLUDES
#include <iostream>
#include <fstream>
#include <string>
#include "Chip8ROM.h"

// NAMESPACES
using namespace std;

namespace Emulator
{
namespace Chip8
{

/*************************************************************/
//
// CLASS: Chip8ROM
//
// DESC: The Chip 8 ROM definition
//
/*************************************************************/

// constructor
// takes nothing
// returns nothing
Chip8ROM::Chip8ROM()
	: _isLoaded(false),
	  _data(NULL)
{
}

// destructor
// takes nothing
// returns nothing
Chip8ROM::~Chip8ROM()
{
}

// loads the ROM
// takes the filename
// returns true upon success, else false
bool Chip8ROM::Load(string fileName)
{
	this->UnLoad();

	bool res = false;
	string line;
	ifstream fp(fileName, ios::in | ios::binary | ios::ate);

	if(fp.is_open())
	{
		ifstream::pos_type size = fp.tellg();

		this->_data = new byte[size];
		this->_size = size;

		fp.seekg(ios::beg, 0);

		fp.read((char*)this->_data, size);

		fp.close();

		res = true;
	}

	this->_isLoaded = res;

	return res;
}

// unloads the ROM
// takes nothing
// returns true upon success, else false
bool Chip8ROM::UnLoad()
{
	bool res = true;

	if(!this->_isLoaded)
		return res;

	if(this->_data != NULL)
	{
		delete [] this->_data;
		this->_data = NULL;
		this->_size = 0;
	}

	this->_isLoaded = false;

	return res;
}

} // end namespace Chip8
} // end namespace Emulator

// EOF: Chip8ROM.cpp